package cn.picclife.mwx.common.web.handler;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import cn.picclife.mwx.common.web.controller.ApiBaseController;

import com.alibaba.fastjson.support.spring.FastJsonJsonView;

/**
 * @author Levi.Wang Spring MVC 统一异常处理
 */
public class ExceptionHandler1 implements HandlerExceptionResolver {
	private static Logger logger = LoggerFactory.getLogger(ExceptionHandler1.class);

	private String defaultErrorView;
	private Integer defaultErrorHttpStatus;

	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

		logger.debug("异常:" + ex.getMessage(), ex);

		// 根据服务端处理器是否是ApiBaseController的实例决定返回数据
		boolean needResponseJson = (((HandlerMethod) handler).getBean() instanceof ApiBaseController) ? true : false;

		ModelAndView mv = new ModelAndView();
		if (needResponseJson) {
			/* 使用FastJson提供的FastJsonJsonView视图返回，不需要捕获异常 */
			FastJsonJsonView view = new FastJsonJsonView();
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("ret", "10000");
			attributes.put("msg", ex.getMessage());
			view.setAttributesMap(attributes);
			response.setStatus(defaultErrorHttpStatus);
			mv.setView(view);
		} else
			mv.setViewName(defaultErrorView);

		return mv;
	}

	public void setDefaultErrorView(String defaultErrorView) {
		this.defaultErrorView = defaultErrorView;
	}

	public void setDefaultErrorHttpStatus(Integer defaultErrorHttpStatus) {
		this.defaultErrorHttpStatus = defaultErrorHttpStatus;
	}
}
